<?php

namespace App\Http\Controllers\WebPage;

/**
 * 返回应用案例
 */

use App\Http\Controllers\Controller;
use App\Http\Models\Cases;
use App\Http\Models\CaseTag;
use App\Http\Requests\WebPage\Cases\CaseIndexRequest;
use App\Services\Utils\ApiChecker;
use App\Services\Utils\ApiResponser;

class CaseController extends Controller
{
    use ApiResponser, ApiChecker;

    const DEFAULT_PER_PAGE = 4;

    const LATEST_COLUMN = 'created_at';

    /**
     * 返回应用案列列表
     *
     *
     * @param CaseIndexRequest $request
     * @return array
     */
    public function index(CaseIndexRequest $request)
    {
        $cases_paginate = Cases::select($this->caseIndexSelectColumns())
            ->filterCaseTagId($request->case_tag_id)
            ->orderBy('sort', 'DESC')
            ->latest(self::LATEST_COLUMN)
            ->paginate($request->per_page ?: self::DEFAULT_PER_PAGE);

        return $this->response(compact('cases_paginate'));
    }

    /**
     * @return array
     */
    private function caseIndexSelectColumns()
    {
        return [
            'id', 'title', 'thumb', 'created_at', 'description', 'sort'
        ];
    }

    public function create()
    {

        $all = [['id' => 0, 'name' => '全部']];

        $tags = CaseTag::select('id', 'name')->get()->all();

        $tags = array_values(array_merge($all, $tags));

        return $this->response(compact('tags'));
    }

}
